<template>
  <!-- 添加或修改.详情抽屉 -->
  <el-drawer
    lock-scroll
    :modal-append-to-body="true"
    append-to-body
    :wrapper-closable="false"
    :title="titleMap[title]"
    :visible.sync="open"
    size="95%"
    :before-close="close"
  >
    <!-- 顶部基本信息 -->
    <div  class="leftBox">
      <div style="padding: 16px;">
        <div v-if="isHaveFlow">
          <div class="leftTop">
            <span>
              <span class="title1">{{ info.processName?info.processName:'-' }}</span>
              <span class="title2">流程编号：{{ info.instanceId?info.instanceId:'-' }}</span>
              <span class="title2">{{ info.startUser?info.startUser:'-' }}</span>
              <span class="title2">{{ info.startUserOrgName?info.startUserOrgName:'-' }}</span>
            </span>
            <span class="time">{{ info.startTime?info.startTime:'-' }}</span>
          </div>
          <el-divider />
        </div>

        <!-- 表单信息 -->
        <div
          class="previewParser" :style="{
            '--size':formConfSize,
            '--color':formConfColor,
            '--bold':formConfBold,
            '--incline':formConfIncline,
            '--underline':formConfUnderline}">
          <Parser
            v-if="isParser" ref="parserForm" :is-detail="isDetail"
            :form-conf="formConf" :is-preview="title!=='add'&&title!=='edit'" @submit="sumbitParser"
            @cancel="cancelForm" />
        </div>
      </div>
    </div>
    <!-- 操作记录、流程图 -->
    <div  class="leftBox" v-if="isHaveFlow">
      <el-tabs v-model="activeName" @tab-click="handleClick(activeName)">
        <el-tab-pane label="操作记录" name="1">
          <div class="operator" style="padding: 16px;">
            <p class="switchbtn" @click="switchFlag=!switchFlag">
              <span v-if="!switchFlag">切换至表格视图</span>
              <span v-if="switchFlag">切换至流程视图</span>
              <svg-icon icon-class="switch2" class="switch2" />
              <svg-icon icon-class="switch" class="switch" />
            </p>
            <flowTimeline v-if="!switchFlag" :time-line-data="timeLineData" />
            <flowDetailInformation v-if="switchFlag" :table-data="tableData" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="2">
          <el-row>
            <el-col :span="18" :xs="24" class="operator">
              <flow :flow-data="flowData" @getCurrentNode="getCurrentNode" />
            </el-col>
            <el-col
              :span="6" :xs="24" class="operator"
              style="border-left: 1px solid #DCDFE6;">
              <div>
                <div class="title5">节点详情</div>
              </div>
              <el-divider />
              <nodeDetali v-if="activityId" :node-data="nodeData" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-drawer>
</template>
<script>
import Parser from '@/framework/views/developer-center/application-center/application-system/applicationFormDesign/components/parser'
import { customFormInfoDetail, customFormDataAdd, customFormDataEdit, customFormDataDetail, getDetailTableList,
  getTitleInfo, flowLowCodeImage, taskViewList, taskList, getActivityDetail } from '@/framework/api/developerCenter/formDesignData'

import flowDetailInformation from '../../../devWorkflow/flowDetail/components/flowDetailInformation.vue'

import flow from '../../../devWorkflow/flowDetail/components/flowImg/flow.vue'
import flowTimeline from '../../../devWorkflow/flowDetail/components/flowTimeline.vue'
import nodeDetali from '../../../devWorkflow/flowDetail/components/nodeDetali.vue'

export default {
  name: 'FormDesignPreview',
  components: {
    Parser,
    flow,
    flowDetailInformation,
    flowTimeline,
    nodeDetali
  },
  props: {
    formId: {
      type: String,
      default: ''
    },
    formJson: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 接口所需参数
    apiProps: {
      type: Object,
      default: () => {
        return {
          id: '123'
        }
      }
    },
    // 接口对象
    api: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 弹出层标题
      title: 'add',
      // 是否显示弹出层
      open: false,
      previewContent: '',
      drawingList: [],
      formConf: {},
      isParser: true,
      titleMap: {
        add: '新增',
        edit: '编辑',
        detail: '详情'
      },
      detailJson: {},
      getValData: {},
      formDataId: '',
      isDetail: false,
      switchFlag: true, // 切换操作记录和流程图的标志
      tableData: [], // 操作记录-表格数据
      timeLineData: [], // 操作记录-时间线图数据
      flowType: '', // 表单类型
      flowData: {}, // 流程图数据
      activeName: '1', // 切换操作记录和流程图的标志
      nodeData: [], // 节点详情数据
      activityId: '', // 点击节点ID
      taskId: '', // 流程ID
      // 流程基本信息
      info: {
        processName: '',
        instanceId: '',
        startUser: '',
        startUserOrgName: '',
        startTime: ''
      },
      // 流程id
      instanceId: '',
      isHaveFlow: ''
    }
  },
  computed: {
    formConfSize() {
      return this.formConf.fontStyle?.fontSize
    },
    formConfColor() {
      return this.formConf.fontStyle?.fontColor
    },
    formConfBold() {
      return this.formConf.fontStyle?.bold ? 'bold' : 'normal'
    },
    formConfIncline() {
      return this.formConf.fontStyle?.incline ? 'italic' : 'normal'
    },
    formConfUnderline() {
      return this.formConf.fontStyle?.underline ? 'underline' : 'none'
    }
  },
  created() {
  },
  methods: {
    cancelForm() {
      this.open = false
      this.$emit('getDataList')
    },
    sumbitParser(param) {
      // this.handleParam1
      const childFormData = {}
      this.handleParam(param.formData.fields, childFormData)
      const params = {
        formData: param.valData,
        childFormData,
        formId: this.formId,
        formDataId: this.formDataId
      }
      // this.detailJson = JSON.parse(JSON.stringify(param.formData))
      if (this.title === 'add') {
        customFormDataAdd(params).then(() => {
          this.$dtModal.msgSuccess('新增成功')
          this.open = false
          this.$emit('getDataList')
        })
      } else {
        customFormDataEdit(params).then(() => {
          this.$dtModal.msgSuccess('编辑成功')
          this.$emit('getDataList')
          this.open = false
        })
      }
    },
    handleParam(fields, childFormData) {
      return (fields || []).reduce((pre, item) => {
        if (item.__config__.layout === 'rowFormItem' || item.__config__.tableColumnType === 'el-collapse') {
          this.handleParam(item.__config__.children, childFormData)
        } else if (item.__config__.tag === 'dt-table') {
          pre[item.tableName] = item.__config__.tableOpts.tableData
        }
        return pre
      }, childFormData)
    },
    // // 取消按钮
    close(done) {
      if (this.title !== 'detail') {
        this.$dtModal.confirm('确认关闭当前页面吗?关闭后不保存当前修改内容').then(() => {
          this.$refs.parserForm.resetForm()
          done()
        })
      } else {
        this.isHaveFlow = false
        done()
      }
    },
    async handleOpen(type, row) {
      this.title = type
      await customFormInfoDetail(this.formId).then((res) => {
        this.formConf = JSON.parse(res.data.formContent)
        this.open = true
        this.isParser = false
        this.isDetail = false
      })
      if (type === 'add') {
        setTimeout(() => {
          this.formDataId = ''
          this.isParser = true
        }, 200)
      } else {
        // 查询主表返回值
        this.formDataId = row.id || row.logId // 日志id是lodId
        await customFormDataDetail({ formId: this.formId, formDataId: row.id || row.logId }).then((res) => {
          this.getValData.formData = res.data
        })
        // 查询从表返回值
        await getDetailTableList({ formId: this.formId, formDataId: row.id || row.logId }).then((res) => {
          this.getValData.childFormData = res.data
          this.dealFromJsonValue(this.getValData)
          this.isParser = true
          this.isHaveFlow = ''
          if (type === 'detail') {
            this.isHaveFlow = row.process_status
            this.formConf.disabled = true // 禁止编辑修改
            this.isDetail = true
            if (this.isHaveFlow) {
              this.getTitle()
              this.gettaskListDetail()
            }
          }
        })
      }
    },
    // 前端 拿到数据后 循环处理成tableOpts格式
    dealFromJsonValue(obj) {
      this.formConf.fields.forEach((cur) => {
        const config = cur.__config__
        if (cur.__vModel__) config.defaultValue = obj.formData[cur.__vModel__]
        if (cur.__config__.children && cur.__config__.layout === 'dtTableDialogRender') {
          // config.tableOpts.tableData = obj.childFormData.map(item => item.tableName === cur.__config__.formId)[0].row
          // config.tableOpts.tableData = obj.childFormData.map(item => item[cur.tableName] === cur.tableName)[0]
          config.tableOpts.tableData = obj.childFormData[cur.tableName]
        }
        this.recursionFcun(cur, obj)
        // if (cur.__config__.children && cur.__config__.layout === 'rowFormItem') {
        //   cur.__config__.children.forEach((item) => {
        //     if (item.__config__.children && item.__config__.layout === 'rowFormItem') {
        //       item.__config__.children.forEach((res) => {
        //         if (res.__vModel__) res.__config__.defaultValue = obj.formData[res.__vModel__]
        //       })
        //     } else if (item.__vModel__) item.__config__.defaultValue = obj.formData[item.__vModel__]
        //   })
        // }
      })
    },
    recursionFcun(data, obj) {
      if ((data.__config__.children && data.__config__.layout === 'rowFormItem') || data.__config__.tableColumnType === 'el-collapse') {
        data.__config__.children.forEach((item) => {
          this.recursionFcun(item, obj)
          if (item.__vModel__) item.__config__.defaultValue = obj.formData[item.__vModel__]
        })
      }
    },
    // 切换操作记录/流程图
    handleClick(activeName) {
      if (activeName === '2') {
        this.getformApplyDetailImg()
      } else {
        this.getTimeLineData()
      }
    },
    // 获取头部标题信息
    getTitle() {
      getTitleInfo({ formId: this.formId, formDataId: this.formDataId }).then((res) => {
        this.info = res.data
        this.instanceId = res.data.instanceId
      })
    },
    // 流程操作记录-表格数据
    gettaskListDetail(id) {
      taskList({ formId: this.formId, formDataId: this.formDataId }).then((res) => {
        this.tableData = res.data
      })
    },
    // 获取操作记录-流程时间线图
    getTimeLineData() {
      taskViewList({ formId: this.formId, formDataId: this.formDataId }).then((res) => {
        this.timeLineData = res.data
      })
    },
    // 获取流程图
    getformApplyDetailImg() {
      flowLowCodeImage({ formId: this.formId, formDataId: this.formDataId }).then((res) => {
        this.flowData = res.data
      })
    },
    // 点击流程图节点，获取节点详情
    getCurrentNode(currentNode) {
      this.activityId = currentNode.element.id
      getActivityDetail({ activityId: this.activityId, instanceId: this.instanceId }).then((res) => {
        this.nodeData = res.data
      })
    }

  }
}
</script>
<style lang="scss" scoped>
::v-deep .drawing-item-copy,::v-deep .drawing-item-delete{
  display: none;
}
::v-deep .el-drawer .el-drawer__body{
  background: #F2F5F8;
  padding:24px 0;
}
.previewParser{
  background: #fff;
  padding: 24px;
  height: auto;
  min-height: 100%;
  width: 1430px;
  margin: auto;
::v-deep .el-form-item__label{
      font-size: var(--size) !important;
      color: var(--color) !important;
      font-weight: var(--bold) !important;
      font-style: var(--incline) !important;
      text-decoration: var(--underline) !important;
}
::v-deep .el-collapse{
  margin-bottom: 22px;
}
}
::v-deep .el-tabs__item {
  padding: 0;
  height: 48px;
  line-height: 48px;
  width: 96px;
  text-align: center;
}
.leftBox:first-child{
  margin-bottom: 16px;
}
.leftBox{
    margin-right: 16px;
    background-color: #fff;
    .leftTop{
      padding: 8px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title1{
        height: 28px;
        font-size: 20px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #2A4ECC;
        line-height: 28px;
        padding-right: 12px;
      }
      .title2{
        height: 24px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #131414;
        line-height: 24px;
        padding: 4px 12px 0;
        border-right: 1px solid #DCDFE6;
      }
      .title2:last-child{
        border: none;
      }
      .time{
        height: 24px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #909399;
        line-height: 24px;
      }

    }
    .operator{
        height: 600px;
        overflow: scroll;
      }
}
::v-deep .el-tabs__header {
    margin: 0 !important;
}
.switch2{
    margin-left: 4px;
    display: block;
  }
  .switch{
    margin-left: 4px;
    display: none;
  }
 .switchbtn{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 14px;
    font-weight: 400;
    line-height: 15px;
    cursor: pointer;
  }
.switchbtn:hover{
  color: #3461FF;
  .switch{
    display: block;
  }
  .switch2{
    display: none;
  }
}
.title5{
  height: 24px;
  font-size: 14px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #131414;
  line-height: 24px;
  margin: 8px auto;
  text-align: center;
}
    </style>

